<script setup lang="ts">
import { useRoute } from 'vue-router'
import { useStorage } from '@vueuse/core'
import { getStoreInfo, getTalkByUserId, getTalkList, getUserInfo } from '~/api/index'
import { beautifyTime } from '~/utils/tools'
import { whetherShareGoods, whetherShareOrder } from '~/pages/template/tools'

const props = defineProps<{
  status: 'connect' | 'close' | 'loading'
}>()
const emit = defineEmits(['talk'])

const route = useRoute()
const user = ref<any>('')
const fetchUserLoading = ref(true)
const fetchTalkLoading = ref(true)
const userType = ref<'STORE' | 'BUYER'>()
const talkList: any = useStorage('talk_list', [])
// const talkDetail = useStorage('talk_detail', {})
const activeTalk = ref<any>(useStorage('talk_detail', {}))
async function fetchUserInfo() {
  // 判断当前是否有Id 用来判断商户/用户
  const id = route.query?.id
  let behavior // 判断是商户还是用户
  try {
    if (id) {
      userType.value = 'BUYER'
      // 用户登录
      behavior = await getUserInfo()
    }
    else {
      userType.value = 'STORE'
      behavior = await getStoreInfo()
    }
    fetchTalkInfo(userType.value === 'STORE' ? 'store' : 'talk')

    fetchUserLoading.value = false
    if (behavior.data.success) {
      user.value = {
        ...behavior.data.result,
        ___role: userType.value,
      }

      const userStorage = useStorage('user', '')
      userStorage.value = JSON.stringify(user.value)
    }
  }
  catch (error) {
    fetchUserLoading.value = false
  }
}

// 获取会话记录
async function fetchTalkInfo(type: 'talk' | 'store') {
  fetchTalkLoading.value = true
  let reserve: string = ''
  if (!type)
    reserve = userType.value === 'STORE' ? 'store' : 'talk'

  try {
    // 获取会话记录
    const talk = await getTalkList(type || reserve)
    fetchTalkLoading.value = false

    if (talk.data.success) {
      talkList.value = talk.data.result
      if (talk.data.result.length)
        handleClickTalk(talk.data.result[0])
    }
  }
  catch (error) {
    fetchTalkLoading.value = false
  }
}
// 点击会话记录
function handleClickTalk(item: any) {
  emit('talk', item)
  activeTalk.value = item
}

function renderType(text: any) {
  if (whetherShareOrder(text))
    return '分享了一个订单'
  if (whetherShareGoods(text))
    return '分享了一个商品'
  return text
}

// 获取聊天
async function fetchTalkUser() {
  await getTalkByUserId(route.query?.id)
}

async function init() {
  const id = route.query?.id

  if (id)
    await fetchTalkUser()

  await fetchUserInfo()
}

defineExpose({
  fetchTalkInfo,
})
onMounted(() => {
  init()
})
</script>

<template>
  <div h-full>
    <div v-auto-animate flex flex-a-c border-b-1px p-16px pb-16px>
      <div v-if="fetchUserLoading">
        <div flex flex-a-c>
          <a-skeleton :animation="true">
            <a-skeleton-shape shape="circle" />
          </a-skeleton>
          <a-skeleton ml-10px w-200px :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
        </div>
      </div>
      <div v-else flex cursor-pointer flex-a-c>
        <!-- 当前账户 -->
        <div v-if="userType === 'STORE'">
          <a-avatar :image-url="user.storeLogo" :size="48" />
        </div>
        <div v-if="userType === 'BUYER'">
          <a-avatar :image-url="user.face" :size="48" />
        </div>
        <div ml-10px>
          <div flex flex-a-c>
            <!-- 买家 -->
            <span v-if="userType === 'BUYER'">
              {{ user.nickName || '暂无资料' }}
            </span>
            <!-- 店家 -->
            <span v-else>
              {{ user.storeName || '暂无资料' }}
            </span>
            <a-tag v-if="user && userType === 'STORE'" ml-5px size="small" color="blue">
              商家
            </a-tag>
          </div>
          <!-- 记录socket状态 在线/离线/连接中 -->
          <div text-12px>
            <a-badge v-if="props.status === 'connect'" text="在线" status="success" />
            <a-badge v-if="props.status === 'close'" text="离线" status="danger" />
            <a-badge v-if="props.status === 'loading'" text="连接中" status="processing" />
          </div>
        </div>
      </div>
    </div>
    <!-- 会话记录 -->
    <div px-16px py-16px>
      会话记录<span>({{ talkList.length }})</span>
    </div>

    <!-- 会话记录 -->
    <div v-auto-animate class="talk-list">
      <div v-if="fetchTalkLoading">
        <div v-for="index in 7" :key="index" flex flex-j-sb flex-a-c p-16px>
          <a-skeleton :animation="true">
            <a-skeleton-shape shape="circle" />
          </a-skeleton>
          <a-skeleton w-230px :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
        </div>
      </div>
      <div v-for="(item, index) in talkList" v-else :key="index" :class="{ active: item.id === activeTalk.id }" class="talk-item" flex flex-j-sb flex-a-c p-16px @click="handleClickTalk(item)">
        <div w-full flex flex-a-c>
          <a-avatar :size="48">
            <img v-if="item.face" h-full w-full alt="avatar" :src="item.face">
            <div v-else>
              {{ item.name }}
            </div>
          </a-avatar>
          <div ml-10px>
            <div>{{ item.name }}</div>
            <div mt-5px class="wes" max-w-100px overflow-hidden text-12px color-gray>
              {{ renderType(item.lastTalkMessage) }}
            </div>
          </div>
        </div>
        <div w-100px text-right text-12px color-gray>
          {{ beautifyTime(item.lastTalkTime) }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.wes {
  /* 多出部分用省略号表示 , 用于一行 */
  overflow: hidden;
  word-wrap: normal;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.talk-item {
  transition: all 0.2s ease-in;
}
.talk-item:hover {
  background: #fafafa;
  cursor: pointer;
}

.active {
  background: #fafafa;
}
.talk-list {
  height: calc(100vh - 140px);
  overflow-y: auto;
}
</style>
